#include <stdio.h>
#include<iostream>
#include<ws2tcpip.h>
#include<string.h>
#include<thread>
#include<mutex>
#pragma comment (lib, "ws2_32.lib")
using namespace std;

mutex mtx;

void recHeart(SOCKET serConn, SOCKADDR_IN clientsocket, PSTR IPaddress) {
	while (1) {
		if (mtx.try_lock()) {
			char sendBuf[100];
			sprintf(sendBuf, "server : welcome %s to server.", inet_ntop(AF_INET, &clientsocket.sin_addr, IPaddress, 16));
			send(serConn, sendBuf, strlen(sendBuf) + 1, 0);
			char receiveBuf[100];
			recv(serConn, receiveBuf, strlen(receiveBuf) + 1, 0);
			const char* quit = "quit";
			if (!strcmp(receiveBuf, quit)) {
				break;
			}
			printf("%s\n", receiveBuf);
			mtx.unlock();
		}
	}
}

int main()
{
	WORD myVersionRequest;
	WSADATA wsaData;
	myVersionRequest = MAKEWORD(1, 1);
	int err;
	err = WSAStartup(myVersionRequest, &wsaData);
	if (!err) {
		printf("Server socket open successfully\n");
	}
	else {
		printf("Server socket open fail");
		return 0;
	}
	SOCKET serSocket = socket(AF_INET, SOCK_STREAM, 0);
	SOCKADDR_IN addr;
	addr.sin_family = AF_INET;
	addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
	addr.sin_port = htons(3000);
	bind(serSocket, (SOCKADDR*)&addr, sizeof(SOCKADDR));
	listen(serSocket, 10);
	SOCKADDR_IN clientsocket;
	int len = sizeof(SOCKADDR);
	SOCKET serConn;
	const char* temp = "127.0.0.1";
	PSTR IPaddress=new char[10];
	strcpy(IPaddress, temp);
	thread t[10];
	int i = 0;
	while (1) {
		serConn = accept(serSocket, (SOCKADDR*)&clientsocket, &len);
		cout << "Client" << inet_ntop(AF_INET, &clientsocket.sin_addr, IPaddress, 16) << "connect successfully" << endl;
		t[i] = thread(recHeart, serSocket, clientsocket, IPaddress);
		t[i].join();
		i++;
	}
	delete []IPaddress;
	closesocket(serConn);
	WSACleanup();
	return 0;
}